#include <stdio.h>
#include <stdlib.h>
#include "FilmList.h"

/* interface functions   */
/* set the list to empty */
static void CopyToNode(Item item, Node *pnode);

// 通过初始化传入的list的指针为NULL
// 这里本质上 List 是 Node*指针, 可以理解为Node*指针头
void InitializeList(List *plist)
{
    plist = NULL;
}

// 因为对链表进行操作,传入的plist(List指针全部是const修饰的,表示不能被函数中的东西更改)
/**
 * @brief 判断list是不是空的
 *
 * @param plist 传入的list的指针参数
 * @return true 是空的
 * @return false  不是空的
 */
bool ListIsEmpty(const List *plist)
{
    if (*plist == NULL)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 * @brief 判断list是不是满的
 *
 * @param plist 传入的list的指针的参数
 * @return true 是满的
 * @return false 不是满的
 */
bool ListIsFull(const List *plist)
{
    Node *pt;
    bool full;

    // 通过malloc()分配空间,没有考虑malloc出错的可能性
    pt = (Node *)malloc(sizeof(Node));
    if (pt == NULL)
        full = true;
    else
        full = false;
    free(pt);

    return full;
}

/* returns number of nodes */
unsigned int ListItemCount(const List *plist)
{
    unsigned int count = 0;
    Node *pnode = *plist; /* pnode是链表的开始指针 */

    // 遍历链表
    while (pnode != NULL)
    {
        ++count;
        pnode = pnode->next; /* set to next node     */
    }

    return count;
}

/* creates node to hold item and adds it to the end of */
/* the list pointed to by plist (slow implementation)  */
bool AddItem(Item item, List *plist)
{
    Node *pnew;     // 新变量用于分配内存
    Node *scan = *plist;    // 得到list的头指针

    pnew = (Node *)malloc(sizeof(Node));
    if (pnew == NULL)
        return false; /* quit function on failure  */

    CopyToNode(item, pnew);
    pnew->next = NULL;
    if (scan == NULL)  /* empty list, so place */
        *plist = pnew; /* pnew at head of list */
    else
    {
        while (scan->next != NULL)
            scan = scan->next; /* find end of list    */
        scan->next = pnew;     /* add pnew to end     */
    }

    return true;
}

/* visit each node and execute function pointed to by pfun */
void Traverse(const List *plist, void (*pfun)(Item item))
{
    Node *pnode = *plist; /* set to start of list   */

    while (pnode != NULL)
    {
        (*pfun)(pnode->item); /* apply function to item */
        pnode = pnode->next;  /* advance to next item   */
    }
}

/* free memory allocated by malloc() */
/* set list pointer to NULL          */
void EmptyTheList(List *plist)
{
    Node *psave;   // 开辟一个新变量,不能直接从头指针开始搞(free之后找不到下一个链表了)

    while (*plist != NULL)
    {
        psave = (*plist)->next; /* save address of next node */
        free(*plist);           /* free current node         */
        *plist = psave;         /* advance to next node      */
    }
}

/* local function definition  */
/* copies an item into a node */
static void CopyToNode(Item item, Node *pnode)
{
    pnode->item = item; /* structure copy */
}
